﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;

namespace com.susi.util.toolkit {
    /// <summary>
    /// 一个只读集合，包装了一个IEnumerable{T}元素
    /// <para>所有方法都是通过Linq实现的</para>
    /// </summary>
    public class CollectionAdapter<T> : ICollection<T> {
        private IEnumerable<T> vs;

        public CollectionAdapter([NotNull] IEnumerable<T> vs)
        {
            this.vs = vs ?? throw new ArgumentNullException(nameof(vs));
        }

        public int Count => vs.Count();

        public bool IsReadOnly => true;

        public void Add(T item)
        {
            vs = vs.Append(item);
        }

        public void Clear()
        {
            vs = Enumerable.Empty<T>();
        }

        public bool Contains(T item)
        {
            return vs.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            vs.CopyTo(array, arrayIndex);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return vs.GetEnumerator();
        }

        public bool Remove(T item)
        {
            if (vs.Contains(item)) {
                vs = vs.Except(new[] {item});
                return true;
            }

            return false;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return vs.GetEnumerator();
        }
    }
}